import { Button, Radio, Row, Checkbox, Input, Select, DatePicker, LocaleProvider } from "antd";
import Form, { WrappedFormUtils } from "antd/lib/form/Form";
import { addon, Permission } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { MainCard } from "src/business/components/style-components/main-card";
import { MainContent } from "src/business/components/style-components/main-content";
import { AppServiceUtility } from 'src/projects/app/appService';
import { isPermission } from "src/projects/app/permission";
import { ROUTE_PATH } from 'src/projects/router';
import { InputType as ListInputType } from "src/business/components/buss-components/sign-frame-layout";
import { ModalSearch } from "src/business/components/buss-components/modal-search";
import { remote } from "src/projects/remote";
import { FileUploadBtn } from "src/business/components/buss-components/file-operation-btn/file-upload-btn";
import { beforeUpload } from "src/projects/app/util-tool";
const { TextArea } = Input;
import zh_CN from 'antd/lib/locale-provider/zh_CN';
const { Option } = Select;

/**
 * 组件：行为护理评估状态
 */
export interface addNursingRecordState extends ReactViewState {
    /** 基础数据 */
    base_data?: any;
    /** 数据id */
    selete_obj?: object;
    /** 项目列表 */
    project_list?: any[];
    /** 长者列表 */
    elder_list?: any[];
    /** 模板列表 */
    template_list?: any[];
    /** 长者 */
    elder?: string;
    /** 模板 */
    template?: string;
    /*申请表里的选项和值 */
    project?: any;
    /*单选按钮的值 */
    radioValue?: any;
    /*多行文本的值 */
    textAreaValue?: any;
    checkValue?: any;
    /** 时间空间显示状态 */
    mode: string;
}
export interface addNursingRecordListFormValues {
    id?: string;
}
/** 时间合集 */
let timedata: string[] = [];
/**
 * 组件：护理评估视图
 */
export class addNursingRecord extends ReactView<addNursingRecordControl, addNursingRecordState> {
    private columns_data_source = [{
        title: '编号',
        dataIndex: 'code',
        key: 'code',
    }, {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
    }, {
        title: '身份证号',
        dataIndex: 'id_card',
        key: 'id_card',
    }, {
        title: '性别',
        dataIndex: 'sex',
        key: 'sex',
    }, {
        title: '出生年月',
        dataIndex: 'birth_date',
        key: 'birth_date',
    }];
    constructor(props: any) {
        super(props);
        this.state = {
            elder_list: [],
            template_list: [],
            project_list: [],
            elder: '',
            template: '',
            project: [],
            mode: "time"
        };
    }
    /** 提交方法 */
    handleSubmit = (e: any) => {
        e.preventDefault();
        const { form } = this.props;
        form!.validateFields((err: Error, values: addNursingRecordListFormValues) => {
            console.log('asdsads>>>', values);
            let obj: any = {}, project_list = [] as any[];
            let list = [];
            // Object.keys(values).map(key => {
            //     console.log('key>>', key);
            //     console.log('obj>>>', obj[key]);
            // });
            let index = -1;
            for (let key in values) {
                if (key.indexOf('___') > 0) {
                    index++;
                    if (key.split('___').length > 2) {
                        list = key.split('___');
                        let radio_list = [];
                        radio_list = list[1].split(';');
                        let new_radio_list: any = [];
                        radio_list.forEach((item: any) => {
                            new_radio_list.push(JSON.parse(item));
                        });
                        let project = {
                            ass_info: {
                                project_name: list[0],
                                dataSource: new_radio_list,
                                selete_type: list[2],
                                value: values[key]
                            },
                            timedata: timedata[index]
                        };
                        project_list.push(project);
                    } else {
                        let project = {
                            ass_info: {
                                project_name: key.split('___')[0],
                                selete_type: key.split('___')[1],
                                value: values[key]
                            },
                            timedata: timedata[index]
                        };
                        project_list.push(project);
                    }

                } else {
                    obj[key] = values[key];
                }
                // });
            }
            obj['project_list'] = project_list;
            console.log("obj》》》》", obj);
            // 把对象组装调用接口，按照每个题目生成一条数据

            AppServiceUtility.nursing_record.update_nursing_recode!({ obj })!
                .then((data: any) => {
                    if (data === 'Success') {
                        this.props.history!.push(ROUTE_PATH.nursingRecord);
                    }
                });
        });
    }
    returnBtn = () => {
        this.props.history!.push(ROUTE_PATH.competenceAssessmentList);
    }
    componentDidMount() {
        AppServiceUtility.person_org_manage_service.get_personnel_elder!({})!
            .then((data: any) => {
                console.log("baocuo", data);
                if (data.result.length > 0) {
                    this.setState({
                        elder_list: data.result
                    });
                }
            });
        AppServiceUtility.assessment_template_service.get_assessment_template_list!({template_type: '护理评估'})!
            .then((data: any) => {
                if (data.result) {
                    this.setState({
                        template_list: data.result
                    });
                }
            });
        if (this.props.match!.params.key) {
            AppServiceUtility.competence_assessment_service.get_competence_assessment_list!({ id: this.props.match!.params.key }, 1, 1)!
                .then((data) => {
                    console.info("编辑的时候的数据", data!.result![0]);
                    if (data!.result![0]) {
                        this.setState({
                            elder: data!.result![0].user_name![0],
                            template: data!.result![0].template![0]['id'],
                            project_list: data!.result![0].project_list
                        });
                    }
                });
        }
    }
    /** 选择模板选择框值改变 */
    template_change = (value: any) => {
        AppServiceUtility.nursing_template.get_nursing_template_list_look!({ id: value })!
            .then((data: any) => {
                console.info("选择模板后返回的数据", data);
                if (data.result.length > 0) {
                    this.setState({
                        project_list: data.result
                    });
                }
            });
    }
    /** 返回按钮 */
    retLisit = () => {
        this.props.history!.goBack();
    }
    handlePanelChange = (value: any, mode: any) => {
        this.setState({ mode });
    }
    Change = (date: any, dateString: string, index: number) => {
        if (dateString) {
            timedata[index] = dateString;
        }
    }
    // handlevalue(e: any) {
    //     console.log(e);
    // }
    render() {
        const redeirect = isPermission(this.props.permission!);
        if (redeirect) {
            return redeirect;
        }

        const { getFieldDecorator } = this.props.form!;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 2 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 22 },
            },
        };
        let modal_search_items_props = {
            type: 'input',
            edit_form_items_props: [
                {
                    type: ListInputType.input,
                    label: "长者名称",
                    decorator_id: "name"
                },
            ],
            columns_data_source: this.columns_data_source,
            service_name: AppServiceUtility.person_org_manage_service,
            service_func: 'get_personnel_elder',
            title: '长者查询',
            select_option: {
                placeholder: "请选择长者",
            }
        };
        let template = this.state.template_list!.map((key, value) => {
            return <Select.Option key={key.id}>{key.template_name}</Select.Option>;
        });
        let project: any = [];
        this.state.project_list!.forEach((item, index) => {
            if (item.hasOwnProperty("ass_info")) {
                if (item.ass_info.hasOwnProperty("selete_type")) {
                    console.log(item.ass_info);
                    if (item.ass_info.selete_type === "1") {
                        let radio_list = '';
                        let item_content: any;
                        if (item.ass_info.hasOwnProperty("dataSource")) {
                            item.ass_info.dataSource.forEach((item: any) => {
                                radio_list = radio_list + JSON.stringify(item) + ";";
                            });
                            radio_list = radio_list.slice(0, radio_list.length - 1);
                            console.log(radio_list, "a-----------------------------------");
                            item_content = (
                                <Form.Item label={item.ass_info.project_name}>
                                    {getFieldDecorator(item.ass_info.project_name + "___" + radio_list + "___1", {
                                        initialValue: item.ass_info.value ? item.ass_info.value : '',
                                        rules: [{
                                            required: false,
                                            message: '请选择' + item.ass_info.project_name,
                                        }],
                                    })(
                                        <div>
                                            <Radio.Group>
                                                {item.ass_info.dataSource!.map((i: any, idx: any) => {
                                                    return <Radio value={i.serial_number} key={idx}>{i.option_content}</Radio>;
                                                })}
                                            </Radio.Group>
                                            <DatePicker
                                                mode={(this.state.mode as any)}
                                                showTime={true}
                                                onPanelChange={this.handlePanelChange}
                                                onChange={(e, datastring) => { this.Change(e, datastring, index); }}
                                            />
                                        </div>
                                    )}
                                </Form.Item>
                            );
                        }
                        project.push(item_content);
                        return project;
                    }
                    if (item.ass_info.selete_type === "2") {
                        let radio_list = '';
                        let item_content: any;
                        if (item.ass_info.hasOwnProperty("dataSource")) {
                            item.ass_info.dataSource.forEach((item: any) => {
                                radio_list = radio_list + JSON.stringify(item) + ";";
                            });
                            radio_list = radio_list.slice(0, radio_list.length - 1);
                            item_content = (
                                <Form.Item label={item.ass_info.project_name} >
                                    {getFieldDecorator(item.ass_info.project_name + '___' + radio_list + '___2', {
                                        initialValue: item.ass_info.value ? item.ass_info.value : '',
                                        rules: [{
                                            required: false,
                                            message: '请选择' + item.ass_info.project_name,
                                        }],
                                    })(
                                        <div>
                                            <Checkbox.Group>
                                                {item.ass_info.dataSource!.map((i: any, idx: any) => {
                                                    return <Checkbox key={idx} value={i.serial_number}>{i.option_content}</Checkbox>;
                                                })}
                                            </Checkbox.Group>
                                            <DatePicker
                                                mode={(this.state.mode as any)}
                                                showTime={true}
                                                onPanelChange={this.handlePanelChange}
                                                onChange={(e, datastring) => { this.Change(e, datastring, index); }}
                                            />
                                        </div>
                                    )}
                                </Form.Item>
                            );
                        }
                        project.push(item_content);
                        return project;
                    }
                    if (item.ass_info.selete_type === "3") {
                        const item_content = (
                            <Form.Item label={item.ass_info.project_name}>
                                {getFieldDecorator(item.ass_info.project_name + '___3', {
                                    initialValue: item.ass_info.value ? item.ass_info.value : '',
                                    rules: [{
                                        required: false,
                                        message: '请输入' + item.ass_info.project_name,
                                    }],
                                })(
                                    <div>
                                        <Input />
                                        <DatePicker
                                            mode={(this.state.mode as any)}
                                            showTime={true}
                                            onPanelChange={this.handlePanelChange}
                                            onChange={(e, datastring) => { this.Change(e, datastring, index); }}
                                        />
                                    </div>
                                )}
                            </Form.Item>
                        );
                        project.push(item_content);
                        return project;
                    }
                    if (item.ass_info.selete_type === "4") {
                        let radio_list = '';
                        let item_content: any;
                        if (item.ass_info.hasOwnProperty("dataSource")) {
                            item.ass_info.dataSource.forEach((item: any) => {
                                radio_list = radio_list + JSON.stringify(item) + ";";
                            });
                            radio_list = radio_list.slice(0, radio_list.length - 1);
                            item_content = (
                                <Form.Item label={item.ass_info.project_name}>
                                    {getFieldDecorator(item.ass_info.project_name + '___' + radio_list + '___4', {
                                        initialValue: item.ass_info.value ? item.ass_info.value : '',
                                        rules: [{
                                            required: false,
                                            message: '请选择' + item.ass_info.project_name,
                                        }],
                                    })(
                                        <div>
                                            <Select defaultValue={item.ass_info.dataSource[0].name} style={{ width: 120 }}>
                                                {item.ass_info.dataSource!.map((i: any, idx: any) => {
                                                    return <Option key={idx} value={i.serial_number}>{i.option_content}</Option>;
                                                })}
                                            </Select>
                                            <DatePicker
                                                mode={(this.state.mode as any)}
                                                showTime={true}
                                                onPanelChange={this.handlePanelChange}
                                                onChange={(e, datastring) => { this.Change(e, datastring, index); }}
                                            />
                                        </div>
                                    )}
                                </Form.Item>
                            );
                        }
                        project.push(item_content);
                        return project;
                    }
                    if (item.ass_info.selete_type === "5") {
                        const item_content = (
                            <Form.Item label={item.ass_info.project_name}>
                                {getFieldDecorator(item.ass_info.project_name + '___5', {
                                    initialValue: item.ass_info.value ? item.ass_info.value : '',
                                    rules: [{
                                        required: false,
                                        message: '请输入' + item.ass_info.project_name,
                                    }],
                                })(
                                    <div>
                                        <TextArea

                                            value={this.state.textAreaValue}
                                            placeholder="请输入"
                                            autosize={{ minRows: 3, maxRows: 5 }}
                                        />
                                        <DatePicker
                                            mode={(this.state.mode as any)}
                                            showTime={true}
                                            onPanelChange={this.handlePanelChange}
                                            onChange={(e, datastring) => { this.Change(e, datastring, index); }}
                                        />
                                    </div>
                                )}
                            </Form.Item>
                        );
                        project.push(item_content);
                        return project;
                    }
                    if (item.ass_info.selete_type === "6") {
                        const item_content = (
                            <Form.Item label={item.ass_info.project_name} >
                                {getFieldDecorator(item.ass_info.project_name + '___6', {
                                    initialValue: item.ass_info.value ? item.ass_info.value : '',
                                    rules: [{
                                        required: false,
                                    }],
                                })(
                                    <div>
                                        <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} />
                                        <DatePicker
                                            mode={(this.state.mode as any)}
                                            showTime={true}
                                            onPanelChange={this.handlePanelChange}
                                            onChange={(e, datastring) => { this.Change(e, datastring, index); }}
                                        />
                                    </div>
                                )}
                            </Form.Item>
                        );
                        project.push(item_content);
                    } else if (item.ass_info.selete_type === "7") {
                        const item_content = (
                            <Form.Item label={item.ass_info.project_name}>
                                {getFieldDecorator(item.ass_info.project_name + '___7', {
                                    initialValue: item.ass_info.value ? item.ass_info.value : '',
                                    rules: [{
                                        required: false,
                                    }],
                                })(
                                    <div>
                                        <FileUploadBtn contents={"button"} action={remote.upload_url} />
                                        <DatePicker
                                            mode={(this.state.mode as any)}
                                            showTime={true}
                                            onPanelChange={this.handlePanelChange}
                                            onChange={(e, datastring) => { this.Change(e, datastring, index); }}
                                        />
                                    </div>
                                )}
                            </Form.Item>
                        );
                        project.push(item_content);
                    }
                }
            } else {
                return true;
            }
        });
        return (
            <LocaleProvider locale={zh_CN}>
                <Form {...formItemLayout}>
                    <MainContent>
                        <MainCard title='护理评估'>
                            <Form.Item label='选择长者'>
                                {getFieldDecorator('elder', {
                                    initialValue: this.state.elder ? this.state.elder : '',
                                    rules: [{
                                        required: true,
                                        message: '请选择长者'
                                    }],
                                })(
                                    <ModalSearch modal_search_items_props={modal_search_items_props} />

                                )}
                            </Form.Item>
                            <Form.Item label='选择模板'>
                                {getFieldDecorator('template', {
                                    initialValue: this.state.template ? this.state.template : '',
                                    rules: [{
                                        required: true,
                                        message: '请选择模板'
                                    }],
                                })(
                                    <Select showSearch={true} onChange={this.template_change}>
                                        {template}
                                    </Select>
                                )}
                            </Form.Item>
                            {project}
                        </MainCard>
                    </MainContent>
                    <Row type='flex' justify='center'>
                        <Button htmlType='submit' type='primary' onClick={this.handleSubmit}>保存</Button>
                        <Button type='ghost' name='返回' htmlType='button' onClick={this.retLisit}>返回</Button>
                    </Row>
                </Form>
            </LocaleProvider>
        );
    }
}

/**
 * 控件：护理评估控件
 * @description 护理评估控件
 * @author
 */
@addon('addNursingRecord', '护理评估控件', '护理评估控件')
@reactControl(Form.create<any>()(addNursingRecord), true)
export class addNursingRecordControl extends ReactViewControl {
    form?: WrappedFormUtils<any>;
    /** 视图权限 */
    public permission?: Permission;
}